/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("jhz_pzbm_js",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.MyTable.IServices;
using VOL.Core.Utilities;
using VOL.Core.DBManager;
using System.Linq;
using Newtonsoft.Json;
using System.Reflection;
using System.Collections;

namespace VOL.MyTable.Controllers
{
    public partial class jhz_pzbm_jsController
    {
        private readonly Ijhz_pzbm_jsService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public jhz_pzbm_jsController(
            Ijhz_pzbm_jsService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 获取选项与选项值的对应关系
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("get_gyxx")]
        public dynamic get_gyxx()
        {
            Hashtable rtn_hst = new Hashtable();
            var yg_xx_list = DBServerProvider.DbContext.Set<yg_xx>().Where(w=>!string.IsNullOrEmpty(w.SHUOM_1)).ToList();//亿格配置变量
            rtn_hst.Add("yg_xx_list", yg_xx_list);
            return rtn_hst;
        }

            [HttpPost, Route("gener_express")]
        public WebResponseContent gener_express(string zc_bm)
        {

            WebResponseContent _webResponse = new WebResponseContent();
            if (zc_bm == "")
            {
                _webResponse.Error("整车编码为空！");
            }
            var jhz_table = DBServerProvider.DbContext.Set<Sys_TableColumn>().Where(w => w.TableName == "jhz_pzbm_js").ToList();//加换装动态表，用于取表格列中文
            var yg_xx_list = DBServerProvider.DbContext.Set<yg_xx>().Where(w => !string.IsNullOrEmpty(w.SHUOM_1)).ToList();//亿格配置变量
            var jhz_pzbm_js_list = DBServerProvider.DbContext.Set<jhz_pzbm_js>().Where(w => w.zc_bm == zc_bm).ToList();
            var jhz_pzbm_js_order = jhz_pzbm_js_list.OrderBy(t => t.zj_bm).ToList();
            var jhz_pzbm_js_g_list = jhz_pzbm_js_order.GroupBy(g => g.zj_bm).Select(g => (new { zj_bm = g.Key, count = g.Count() })).ToList();//根据组件编码进行分组
            foreach (var item in jhz_pzbm_js_g_list)
            {
                if (item.count == 1)//只有一个配置变量
                {
                    dyone(jhz_pzbm_js_list, item, jhz_table, yg_xx_list);
                   
                }
                else//多行or情况
                {
                    //Console.WriteLine(item.zj_bm+"=="+ item.count);
                    var g1 = jhz_pzbm_js_list.Where(w => w.zj_bm == item.zj_bm).ToList();
                    string express_or = "";
                    string express_or_zh = "";
                    foreach (var g_item in g1)//组合成or
                    {
                        string tt = comm_express(jhz_pzbm_js_list, g_item, jhz_table, yg_xx_list);
                        express_or = express_or + " or "+ tt.Split(",")[0];
                        express_or_zh = express_or_zh + " or " + tt.Split(",")[1];
                        g_item.expression = "";
                        g_item.expression_zh = "";
                        DBServerProvider.DbContext.Update(g_item);//清空or行
                        DBServerProvider.DbContext.SaveChanges();
                    }
                    express_or = express_or.Trim().Substring(2);
                    express_or_zh = express_or_zh.Trim().Substring(2);
                    g1[0].expression = express_or.Trim();//写入or最后一行
                    g1[0].expression_zh = express_or_zh.Trim();
                    DBServerProvider.DbContext.Update(g1[0]);
                    DBServerProvider.DbContext.SaveChanges();
                }

            }
            return _webResponse.OK("生成成功！");

        }
        /// <summary>
        /// item为一个配置变量的值
        /// </summary>
        /// <param name="jhz_pzbm_js_list"></param>
        /// <param name="item"></param>
        /// <param name="jhz_table"></param>
        /// <param name="yg_xx_list"></param>
        void dyone(List<jhz_pzbm_js> jhz_pzbm_js_list, dynamic item,List<Sys_TableColumn> jhz_table,List<yg_xx> yg_xx_list)
        {
            jhz_pzbm_js js = jhz_pzbm_js_list.Where(w => w.zj_bm == item.zj_bm).FirstOrDefault();
            Type type = typeof(jhz_pzbm_js);
            string tt=comm_express(jhz_pzbm_js_list, js, jhz_table, yg_xx_list);
            
            js.expression = tt.Split(",")[0].Trim();
            js.expression_zh = tt.Split(",")[1].Trim();
           
            DBServerProvider.DbContext.Update(js);
            DBServerProvider.DbContext.SaveChanges();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="jhz_pzbm_js_list"></param>
        /// <param name="js">需要解析的一条记录</param>
        /// <param name="jhz_table"></param>
        /// <param name="yg_xx_list"></param>
        /// <returns></returns>
        string comm_express(List<jhz_pzbm_js> jhz_pzbm_js_list, jhz_pzbm_js js, List<Sys_TableColumn> jhz_table, List<yg_xx> yg_xx_list)
        {
            Type type = typeof(jhz_pzbm_js);
            var pzbl_array = js.pz_bl.Split("+");
            string express_zh = "";
            string express_code = "";
            for (int i = 0; i < pzbl_array.Length; i++)
            {
                if (pzbl_array.Length == 1)//中间没+号
                {
                    string tt = "";
                    try
                    {
                            tt = jhz_table.Where(w => w.ColumnCnName == pzbl_array[0]).Select(s => s.ColumnName).FirstOrDefault();
                            PropertyInfo property = type.GetProperty(tt);
                            object value = property.GetValue(js);
                            if (value != null)
                            {
                                        express_zh = pzbl_array[0] + "=" + value.ToString();//中文表达式
                                        string xuanx = yg_xx_list.Where(w => w.SHUOM == pzbl_array[0]).Select(s => s.TEZM).FirstOrDefault();
                            //  var xuanx_z1 = yg_xx_list.Where(w => w.SHUOM.Trim().Contains(pzbl_array[i])).ToList();//查询字符中有特殊字符，如  旗舰+滑动
                            //string xuanx_z = xuanx_z1.Where(w => w.SHUOM_1.Contains((string)value ?? "")).Select(s => s.XUANX).FirstOrDefault();//查询字符中有特殊字符，如  旗舰+滑动
                          //   string xuanx_z = yg_xx_list.Where(w => w.SHUOM.Trim().Contains(pzbl_array[i]) && w.SHUOM_1.Contains((string)value ?? "")).Select(s => s.XUANX).FirstOrDefault();//查询字符中有特殊字符，如  旗舰+滑动
                            string xuanx_z = yg_xx_list.Where(w => !string.IsNullOrEmpty(w.SHUOM_1)&& w.SHUOM_1.Contains((string)value ?? "") && w.SHUOM.Contains(pzbl_array[i])).Select(s => s.XUANX).FirstOrDefault();//查询字符中有特殊字符，如  旗舰+滑动
                           // var xuanx_z11 = yg_xx_list.Where(w => w.SHUOM_1==(value.ToString()) && w.SHUOM==(pzbl_array[i]));//查询字符中有特殊字符，如  旗舰+滑动
                           // string xuanx_z = xuanx_z11.Select(s => s.XUANX).FirstOrDefault();
                            /* string xuanx_z_sql = "select * from yg_xx where CHARINDEX('" + value.ToString() + "', SHUOM_1) > 0 and CHARINDEX('" + pzbl_array[i] + "',SHUOM)>0";//防止用户输入特殊字符
                             var xuanx_z_array= DBServerProvider.SqlDapper.QueryList<dynamic>(xuanx_z_sql,null).ToList();
                             string xuanx_z = "";
                             if (xuanx_z_array.Count > 0)
                             {
                                 xuanx_z = xuanx_z_array[0].XUANX;
                             }*/
                            express_code = xuanx + "=" + xuanx_z;//编码表达式
                        }
                        else
                        {
                            throw new Exception("[" + pzbl_array[0] + "]对应的选项值没填,组件编码为：" + js.zj_bm);
                        }
                    }
                    catch (Exception )
                    {
                        throw new Exception("["+ express_zh + "],选项不存在,组件编码为：" + js.zj_bm);
                    }
                }
                else//中间有 + 号
                {
                    //string tt = jhz_table.Where(w => w.ColumnCnName == pzbl_array[i]).Select(s => s.ColumnName).FirstOrDefault();
                    string tt = "";
                    try
                    {
                            tt = jhz_table.Where(w => w.ColumnCnName == pzbl_array[i]).Select(s => s.ColumnName).FirstOrDefault();
                            PropertyInfo property = type.GetProperty(tt);
                            object value = property.GetValue(js);
                        if (value != null)
                        {
                            express_zh = express_zh + " and " + pzbl_array[i] + "=" + value.ToString();//中文表达式
                                                                                                       //express_zh = express_zh.Trim().Substring(3);
                            string xuanx = yg_xx_list.Where(w => w.SHUOM == pzbl_array[i]).Select(s => s.TEZM).FirstOrDefault();
                            var xuanx_z1 = yg_xx_list.Where(w => w.SHUOM == pzbl_array[i]).ToList();//查询字符中有特殊字符，如  旗舰+滑动

                            string xuanx_z = xuanx_z1.Where(w => w.SHUOM_1.Contains((string)value ?? "")).Select(s => s.XUANX).FirstOrDefault();//查询字符中有特殊字符，如  旗舰+滑动
                          
                            //string xuanx_z = yg_xx_list.Where(w => w.SHUOM_1.Contains(value.ToString()??"") && w.SHUOM.Trim().Contains(pzbl_array[i])).Select(s => s.XUANX).FirstOrDefault();
                            /*string xuanx_z_sql = "select * from yg_xx where CHARINDEX('" + value.ToString() + "', SHUOM_1) > 0 and CHARINDEX('" + pzbl_array[i] + "',SHUOM)>0";//防止用户输入特殊字符
                            var xuanx_z_array = DBServerProvider.SqlDapper.QueryList<dynamic>(xuanx_z_sql, null).ToList();
                            string xuanx_z = "";
                            if (xuanx_z_array.Count > 0)
                            {
                                xuanx_z = xuanx_z_array[0].XUANX;
                            }*/
                            express_code = express_code + " and " + xuanx + "=" + xuanx_z;//编码表达式
                            express_code = express_code.Trim();
                            //  express_code = express_code.Trim().Substring(3);
                        }
                        else { //说明没找到对应的选项值
                            throw new Exception("[" + pzbl_array[i] + "]对应的选项值没填,组件编码为：" + js.zj_bm);
                        }
                    }
                    catch (Exception ex )
                    {
                        if (ex.Message != null)
                            throw new Exception(ex.Message);
                        else {
                            throw new Exception("[" + express_zh + "],选项不存在,组件编码为：" + js.zj_bm);
                        }
                        
                    }

                }

            }
            if (!string.IsNullOrEmpty(express_zh))
            {
                if (express_zh.Trim().Substring(0, 3) == "and")
                {
                    express_zh = express_zh.Trim().Substring(3);
                    express_code = express_code.Trim().Substring(3);//去掉and
                }
            }
            

            return express_code.Trim() + "," + express_zh.Trim();
        }
    }
}
